import { Select, Typography } from 'antd';
import type { DefaultOptionType } from 'rc-select/lib/Select';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useSearchParams } from 'react-router-dom';

import { PrismCode } from '@/components/SourceCode';
import { VulnerableProps } from '@/components/VulnerableTemplate/type';
import xssCode from '@/pages/vulnerable/code/xss';
import { judgeScript } from '@/utils/judgeAttack';
import messageBox from '@/utils/messageBox';

const { Title } = Typography;

const codeProps: PrismCode = {
  language: 'tsx',
  code: xssCode.dom,
};

const Vulnerable: React.FC = () => {
  const { t } = useTranslation();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();

  const options = useMemo(() => {
    let nativeOptions: DefaultOptionType[] = [
      {
        label: 'Chinese',
        value: 'Chinese',
      },
      {
        label: 'English',
        value: 'English',
      },
      {
        label: 'German',
        value: 'German',
      },
      {
        label: 'French',
        value: 'French',
      },
    ];

    if (searchParams?.get('default') && searchParams.get('default')!.length !== 0) {
      const defaultLang = searchParams.get('default')!;
      nativeOptions.unshift({
        label: '-------',
        value: '-------',
        disabled: true,
      });
      nativeOptions.unshift({
        label: <div dangerouslySetInnerHTML={{ __html: defaultLang }} />,
        value: defaultLang + ' ',
        disabled: true,
      });
      if (judgeScript(defaultLang)) messageBox.info({ content: t('xss.insertScript') });
    }

    return nativeOptions;
  }, [searchParams]);

  const handleSelect = (val: string) => {
    console.log(searchParams.get('default'));
    navigate(`/xss/dom?default=${val}`, {
      replace: true,
    });
  };

  return (
    <Typography>
      <Title italic level={4}>
        {t('xss.dom.title')}
      </Title>
      <Select
        defaultValue={
          searchParams?.get('default') && searchParams.get('default')!.length !== 0
            ? searchParams.get('default')!
            : 'Chinese'
        }
        options={options}
        onSelect={handleSelect}
      />
    </Typography>
  );
};

const XssDom: VulnerableProps = {
  vulnerable: <Vulnerable />,
  codeProps,
  causesSolutions: {
    type: 'xss',
    hasCompare: true,
    solutions: 5,
  },
};

export default XssDom;
